<template>
  <div>
    <r-search
      :searchForm="searchForm"
      :searchHandle="searchHandle"
      :searchData="searchData"
    />
    <r-table
      :tableHandles="tableHandles"
      :isSelection="false"
      :isIndex="false"
      :isPagination="true"
      :tableData="tableData"
      :tableCols="tableCols"
      :tablePage="tablePage"
      :isHandle="true"
      @refresh="init()"
    >
    </r-table>
    <!-- Edit按钮打开的表单 -->
    <r-form
      :formRules="formRules"
      :formHandle="formHandle"
      :formData="formData"
      :formCols="formCols"
      ref="elForm"
      labelWidth="250px"
      dialogWidth="800px"
      :isHandle="true"
    >
      <div
        v-show="isType"
        v-for="(item, index) in mealBaseRateEntities"
        :key="index"
        style="margin-bottom: 10px;"
      >
        <div style="position: relative;width: 75%;left:20%">
          <span style="margin-right: 16px;">充电功率(瓦)</span>
          <el-input
            v-model="item.rateOfWork"
            placeholder="Please Input"
            size="small"
            style=" width: 15%"
          />
          <span style="margin-right: 20px;margin-left: 70px;">费用(元)</span>
          <el-input
            v-model="item.cost"
            placeholder="Please Input"
            size="small"
            style=" width: 20%"
          />
          <i
            class="el-icon-delete"
            @click="deleteInput(item, index)"
            style="color:red;fontSize:25px"
          ></i>
        </div>
      </div>
      <div>
        <i
          v-show="isType"
          class="el-icon-circle-plus-outline"
          @click="addInput"
          style="color:blue;fontSize:25px;margin-left: 605px;"
        ></i>
        <!-- <i v-show="isType" class="el-icon-refresh-right" @click="qingkongInput(item, index)"
          style="color:blue;fontSize:25px;margin-left: 645px;"></i> -->
      </div>
    </r-form>

    <!-- <div>
      <el-dialog title="Edit" :visible.sync="dialogFormVisible">
        <el-form :model="formDatas">
          <el-form-item label="Package Name" label-width="80px">
            <el-input v-model="formDatas.mealName" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item label="PackageType" label-width="80px">
            <el-select v-model="formDatas.type" placeholder="PackageType">
              <el-option label="按时间收费" value="1"></el-option>
              <el-option label="按电量收费" value="2"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="收费标准（每小时/每度电）" :label-width="formLabelWidth">
            <el-input v-model="formDatas.mealName" autocomplete="off"></el-input><span>元</span>
          </el-form-item>
          <el-form-item label=" 充电功率（瓦）" :label-width="formLabelWidth">
            <el-input v-model="cost" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item label="Employ费用" :label-width="formLabelWidth">
            <el-input v-model="rateOfWork" autocomplete="off"></el-input>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="dialogFormVisible = false">Cancel</el-button>
          <el-button type="primary" @click="dialogFormVisible = false">Confirm</el-button>
        </div>
      </el-dialog>
    </div> -->
    <!-- Details页 -->
    <Associated_devices
      :res="Associated_devices_data"
      v-if="Associated_devices_data.show"
      v-on:Associated_devices_call="Associated_devices_call"
    ></Associated_devices>
  </div>
</template>
<script>
import Associated_devices from "./cus/Associated_devices";
export default {
  components: {
    Associated_devices
  },
  data() {
    return {
      // formDatas: {
      //   mealName: '',
      //   type: '',
      //   price: '',
      //   mealBaseRateEntities: [
      //     {
      //       rateOfWork: "", //充电功率（瓦）
      //       cost: "", //费用 (元)
      //     }
      //   ]
      // },
      mealBaseRateEntities: [], //接收按电量收费的Data
      formData: {
        mealBaseRateEntities: [],
        mealName: "",
        price: "",
        type: "",
        rateOfWork: [], //充电功率（瓦）
        cost: [] //费用 (元)
      },
      formLabelWidth: "120px",
      dialogFormVisible: false,
      newDianliang: 1,
      gonglipicess: {},
      cost: "",
      rateOfWork: "",
      isType: false,
      Associated_devices_data: {
        show: false,
        id: ""
      },
      searchData: {
        type: ""
      },
      // Please SelectPackageType下拉框
      searchForm: [
        {
          type: "select",
          prop: "type",
          placeholder: "PackageType",
          width: 150,
          options: [
            { label: "按时间收费", value: 1 },
            { label: "按功率收费", value: 2 }
          ]
        }
      ],
      // Search按钮
      searchHandle: [
        {
          label: "Search",
          type: "success",
          icon: "el-icon-search",
          handle: e => this.init()
        }
      ],
      // AddPackage 按钮
      tableHandles: [
        {
          label: "AddPackage",
          type: "primary",
          handle: e =>
            this.elFormVisible(
              // 按电量收费初始化
              (this.mealBaseRateEntities = [
                {
                  rateOfWork: "", //充电功率（瓦）
                  cost: "" //费用 (元)
                }
              ])
            )
        }
      ],
      tableData: [],
      // 分页列表的格式
      tableCols: [
        {
          label: "序号",
          prop: "id"
        },
        {
          label: "充电Package名",
          prop: "mealName"
        },
        {
          label: "PackageType",
          prop: "type",
          formatter: row => {
            if (row.type == 1) {
              return "按时间收费";
            } else if (row.type == 2) {
              return "按功率收费";
            }
          }
        },
        {
          label: "收费标准",
          prop: "price"
        },
        {
          label: "关联设备",
          prop: "deviceNum"
        },
        {
          label: "Update Time",
          prop: "ctime"
        },
        {
          label: "EnableStatus",
          type: "switch",
          prop: "status",
          values: [1, 2],
          change: row => this.changestate(row)
        },

        {
          label: "Operations",
          type: "button",
          width: 300,
          btnList: [
            {
              label: "已关联设备",
              type: "primary",
              handle: row => {
                this.Associated_devices_data.id = row.id;
                this.Associated_devices_data.show = true;
              }
            },
            {
              label: "Edit",
              type: "primary",
              handle: row => this.elFormDetail(row)
              // handle: ((row) => {
              //   this.dialogFormVisible = true
              //   this.bianjiForm(row)
              // })
            },
            {
              label: "Delete",
              type: "primary",
              handle: row => this.del(row)
            }
          ]
        }
      ],
      // 分页的数量、页码与总条数
      tablePage: { limit: 10, page: 1, total: 0 },
      // Edit页面的form表单的Data源

      // Edit页面的form表单格式
      formCols: [
        { type: "input", label: "Package Name", width: 350, prop: "mealName" },
        {
          type: "select",
          label: "PackageType",
          width: 350,
          prop: "type",
          options: [
            { label: "按时间收费", value: 1 },
            { label: "按功率收费", value: 2 }
          ]
        },
        {
          type: "input",
          label: "收费标准（每小时）",
          width: 350,
          prop: "price",
          remark: "元",
          isShow: () => (this.isType ? false : true)
        }
        // {
        //   type: "input", label: "充电功率(瓦)", width: 350, prop: "rateOfWork",
        //   isShow: () => this.isType ? true : false,
        // },
        // {
        //   type: "input", label: "费用", width: 350, prop: "cost",
        //   isShow: () => this.isType ? true : false
        // },
        // {
        //   type: "select", label: "充电功率(瓦)", width: 350, prop: "rateOfWork",
        //   options: [{ label: '210', value: 1 }, { label: '220', value: 2 }, { label: '480', value: 3 }],
        //   isShow: () => this.isType ? true : false
        // },
      ],
      // Edit页面form表单的消息Hint
      formRules: {
        mealName: [
          { required: true, message: "Please Input", trigger: "blur" }
        ],
        price: [{ required: true, message: "Please Input", trigger: "blur" }],
        type: [{ required: true, message: "Please Select", trigger: "blur" }]
      },
      // Edit页面的 Confirm Cancel按钮
      formHandle: [
        {
          label: "Cancel",
          handle: e => this.elFormVisible()
        },
        {
          label: "Confirm",
          type: "success",
          handle: e => this.elFormSubmit()
        }
      ]
    };
  },
  methods: {
    // 从后台拿到分页列表的Data
    async init() {
      let parm = {
        ...this.searchData,
        ...{
          pageNum: this.tablePage.page,
          pageSize: this.tablePage.limit
        }
      };
      let res = await this.apis.mealCharge_list(parm);
      if (res) {
        this.tableData = res.rows || [];
        this.tablePage.total = res.total;
      }
    },
    // 按电量收费Delete的办法
    async deleteInput(item, index) {
      let res = await this.apis.webMealBaseRateDel(item.id);
      console.log(res);
      if (this.mealBaseRateEntities.length <= 3) {
        this.$message({
          message: "Add按电量收费不得少于三条",
          type: "error"
        });
        return false;
      }
      this.mealBaseRateEntities.splice(index, 1);
    },
    // 按电量收费增加的办法
    addInput() {
      this.mealBaseRateEntities.push({
        rateOfWork: "",
        cost: ""
      });
    },
    // qingkongInput() {
    //   this.mealBaseRateEntities = this.mealBaseRateEntities.forEach((item) => {
    //     item.cost = '', item.rateOfWork = ''
    //   })
    // },
    // Edit 按钮调用的方法
    async elFormDetail(row) {
      let res = await this.apis.webMealCharge(row.id);
      if (res.code == 200) {
        this.formData = res.data;
        this.mealBaseRateEntities = res.data.mealBaseRateEntities;
      }

      Object.keys(this.formData).forEach(key => {
        this.formData[key] = row[key];
      });
      this.elFormVisible();
    },
    // Edit （Add）页面的Confirm按钮 调用的方法
    async elFormSubmit() {
      this.$refs.elForm.$refs.ruleForm.validate(async valid => {
        if (valid) {
          // 当选中按电量收费时，要限制是否有三条
          if (this.newDianliang == 2) {
            if (this.mealBaseRateEntities.length < 3) {
              this.$message({
                message: "Add按电量收费不得少于三条",
                type: "error"
              });
              return false;
            }
            // else if (this.mealBaseRateEntities.length >= 3) {

            //   var arrs = this.mealBaseRateEntities.forEach((item) => {

            //   })
            //   if (arrs.length == 0) {
            //     console.log(111111111);
            //     alert(111111)

            //   }
            // }
          }
          // 把按电量收费数组this.mealBaseRateEntities与formData对象，组成新的对象，作为Data源，发送请求
          let mealBaseRateEntities = this.mealBaseRateEntities;
          this.formData.mealBaseRateEntities = mealBaseRateEntities;
          // 有id就是Edit的
          if (this.formData.id) {
            const res = await this.apis.mealCharge_update({ ...this.formData });
          }
          // 没id就是Add的
          else {
            const res = await this.apis.mealCharge_save({ ...this.formData });
            // this.apis.MealBaseRate({ ...this.formData }).then((res) => {
            //   console.log(res);
            // })
          }

          this.init();
          this.elFormVisible();
        }
      });
    },
    // Delete按钮调用的方法
    del(row) {
      this.$confirm(`DeleteCurrent这条Data`, "Hint", {
        confirmButtonText: "Confirm",
        cancelButtonText: "Cancel",
        type: "warning"
      }).then(async () => {
        const res = await this.apis.mealCharge_del({
          id: row.id
        });

        this.init();

        this.$message({
          message: "Operations Success！",
          type: "success"
        });
      });
    },
    // EnableStatus按钮调用的方法
    async changestate(row) {
      const res = await this.apis.mealCharge_update({
        id: row.id,
        status: row.status
      });
      this.$message({
        message: "Operations Success！",
        type: "success"
      });
    },

    Associated_devices_call() {
      this.Associated_devices_data.show = false;
    }
  },
  watch: {
    "formData.type": {
      deep: true,
      handler: function(newV, oldV) {
        this.newDianliang = 1;
        // 当PackageType为2，即按电量收费
        if (newV == 2) {
          this.newDianliang = newV;
          (this.isType = true), //Control按电量收费时会出现的表单
            console.log(newV);
        } else {
          this.isType = false;
        }
      }
    }
  },
  computed: {},
  mounted() {
    this.init();
  }
};
</script>
<style scoped lang="scss">
.el-icon-search {
  margin-right: 10px;
}

.Tip {
  margin-left: 20px;
}
</style>
